package org.an.proj.contacts.util;

import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.an.proj.contacts.net.service.retrofit.coverter.GithubTypeAdapterFactory;
import org.an.proj.contacts.tool.gson.IgnoreStrategy;

/**
 * Created by an on 2016/11/5.<br/>
 * 数据解析工具类
 */

public class DataParseUtil {

  private static final String TAG = "DataParseUtil";

  public static final GsonBuilder mGsonBuilder =
      new GsonBuilder().setExclusionStrategies(new IgnoreStrategy());

  /**
   * GSON转换类
   */
  public static final Gson mGson = mGsonBuilder.create();

  /**
   * 专门用于解析github服务器json,忽略github reponse的外层包裹，直接得到content对应部分
   */
  public static Gson mGithubGson =
      new GsonBuilder().registerTypeAdapterFactory(new GithubTypeAdapterFactory()).create();

  public static String toJson(Object object) {
    return mGson.toJson(object);
  }

  /**
   * 将JSON字符串转化成对象
   */
  public static <T> T fromJson(String json, Class<T> cls) {
    try {
      return mGson.fromJson(json, cls);
    } catch (JsonSyntaxException e) {
      Log.e(TAG, e.toString());
    }
    return null;
  }

  /**
   * 将字符串转化成对象集合
   */
  @Nullable public static <T> List<T> toList(String json, Class<T> cls) {
    Type type = new TypeToken<ArrayList<JsonObject>>() {
    }.getType();
    ArrayList<T> arrayList = null;
    try {
      ArrayList<JsonObject> jsonObjects = mGson.fromJson(json, type);
      if (jsonObjects != null && jsonObjects.size() > 0) {
        arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
          arrayList.add(mGson.fromJson(jsonObject, cls));
        }
      }
    } catch (JsonSyntaxException e) {
      Log.e(TAG, e.toString());
    }
    return arrayList;
  }
}
